package com.example.redislearning.controller;

import com.example.redislearning.service.LearningProgressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 学习进度管理控制器
 * 提供学习进度相关的REST API接口
 */
@RestController
@RequestMapping("/api/learning")
@CrossOrigin(origins = "*")
public class LearningProgressController {

    @Autowired
    private LearningProgressService learningProgressService;

    /**
     * 开始学习课程
     */
    @PostMapping("/start")
    public ResponseEntity<Map<String, Object>> startLearning(
            @RequestParam Integer userId,
            @RequestParam Integer courseId) {

        try {
            boolean success = learningProgressService.startLearning(userId, courseId);

            if (success) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "开始学习成功"
                ));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                        "success", false,
                        "message", "开始学习失败，可能未购买课程或已在学习中"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "success", false,
                    "message", "开始学习失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 更新学习进度
     */
    @PostMapping("/progress")
    public ResponseEntity<Map<String, Object>> updateProgress(
            @RequestParam Integer userId,
            @RequestParam Integer courseId,
            @RequestParam Double progress) {

        try {
            boolean success = learningProgressService.updateProgress(userId, courseId, progress);

            if (success) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "更新进度成功",
                        "progress", progress
                ));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                        "success", false,
                        "message", "更新进度失败，进度值应在0-100之间"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "success", false,
                    "message", "更新进度失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 记录学习时长
     */
    @PostMapping("/study-time")
    public ResponseEntity<Map<String, Object>> recordStudyTime(
            @RequestParam Integer userId,
            @RequestParam Integer courseId,
            @RequestParam Integer minutes) {

        try {
            boolean success = learningProgressService.recordStudyTime(userId, courseId, minutes);

            if (success) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "记录学习时长成功",
                        "minutes", minutes
                ));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                        "success", false,
                        "message", "记录学习时长失败，时长必须大于0"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "success", false,
                    "message", "记录学习时长失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取学习进度
     */
    @GetMapping("/progress")
    public ResponseEntity<Map<String, Object>> getLearningProgress(
            @RequestParam Integer userId,
            @RequestParam Integer courseId) {

        try {
            Double progress = learningProgressService.getLearningProgress(userId, courseId);

            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "progress", progress
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "success", false,
                    "message", "获取学习进度失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取学习时长
     */
    @GetMapping("/study-time")
    public ResponseEntity<Map<String, Object>> getStudyTime(
            @RequestParam Integer userId,
            @RequestParam(required = false) Integer courseId) {

        try {
            Integer studyTime = learningProgressService.getStudyTime(userId, courseId);

            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "studyTime", studyTime
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "success", false,
                    "message", "获取学习时长失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取学习进度列表
     */
    @GetMapping("/progress-list")
    public ResponseEntity<Map<String, Object>> getLearningProgressList(
            @RequestParam Integer userId) {

        try {
            List<Map<String, Object>> progressList = learningProgressService.getLearningProgressList(userId);

            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "data", progressList
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "success", false,
                    "message", "获取学习进度列表失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取学习时长排行榜
     */
    @GetMapping("/study-time-ranking")
    public ResponseEntity<Map<String, Object>> getStudyTimeRanking(
            @RequestParam(defaultValue = "10") int limit) {

        try {
            List<Map<String, Object>> ranking = learningProgressService.getStudyTimeRanking(limit);

            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "data", ranking
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "success", false,
                    "message", "获取学习时长排行榜失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取已完成课程
     */
    @GetMapping("/completed-courses")
    public ResponseEntity<Map<String, Object>> getCompletedCourses(
            @RequestParam Integer userId) {
        try {
            Set<Integer> completedCourses = learningProgressService.getCompletedCourses(userId);

            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "data", completedCourses
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "success", false,
                    "message", "获取已完成课程失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取学习统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getLearningStats(
            @RequestParam Integer userId) {

        try {
            Map<String, Object> stats = learningProgressService.getLearningStats(userId);

            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "data", stats
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "success", false,
                    "message", "获取学习统计失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 标记课程完成
     */
    @PostMapping("/complete")
    public ResponseEntity<Map<String, Object>> markCourseCompleted(
            @RequestParam Integer userId,
            @RequestParam Integer courseId) {

        try {
            boolean success = learningProgressService.markCourseCompleted(userId, courseId);

            if (success) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "课程标记完成成功"
                ));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                        "success", false,
                        "message", "课程标记完成失败"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "success", false,
                    "message", "课程标记完成失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 保存进度到数据库
     */
    @PostMapping("/save-progress")
    public ResponseEntity<Map<String, Object>> saveProgressToDatabase(
            @RequestParam Integer userId,
            @RequestParam Integer courseId) {

        try {
            boolean success = learningProgressService.saveProgressToDatabase(userId, courseId);

            if (success) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "进度保存到数据库成功"
                ));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                        "success", false,
                        "message", "进度保存到数据库失败"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "success", false,
                    "message", "进度保存到数据库失败: " + e.getMessage()
            ));
        }
    }
}